﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Text;
using System.Windows.Input;
using Avalonia;
using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Utilities;
using AvaloniaApplication1.Validations;

namespace AvaloniaApplication1.Converters
{
    public class TestValiteConverter : IValueConverter
    {


        public TestValidation TestValidation { get; set; }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {

            ValidationResult validationResult = TestValidation.Validate(value, culture);
            if (validationResult != ValidationResult.Success)
            {
                return new BindingNotification(new InvalidCastException(validationResult.ErrorMessage), BindingErrorType.DataValidationError);
            }

            if (value == null)
            {
                return targetType.IsValueType ? AvaloniaProperty.UnsetValue : null;
            }

            //if (typeof(ICommand).IsAssignableFrom(targetType) && value is Delegate d && d.Method.GetParameters().Length <= 1)
            //{
            //    return new MethodToCommandConverter(d);
            //}

            if (TypeUtilities.TryConvert(targetType, value, culture, out object result))
            {
                return result;
            }

            string message;

            if (TypeUtilities.IsNumeric(targetType))
            {
                message = $"'{value}' 不是一个正确的数值";
            }
            else
            {
                message = $"Could not convert '{value}' to '{targetType.Name}'.";
            }

            return new BindingNotification(new InvalidCastException(message), BindingErrorType.Error);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Convert(value, targetType, parameter, culture);
        }
    }

    public class Student
    {
        //public Student(string firstName, string lastName)
        //{
        //    FirstName = firstName;
        //    LastName = lastName;
        //}

        //public Student()
        //{
        //    FirstName = "P";
        //    LastName = "D";

        //}

        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
